import ctypes
import os
import time

import cv2
import numpy as np

#1载入库
libLoad = ctypes.cdll.LoadLibrary
sharelib = libLoad("./build/libpython_share_memory.so")

def get_pc_array():
    sharelib.get_pc_array.restype =ctypes.POINTER(ctypes.c_float)  #c_char_p
    #获取输出图像数据指针
    pc_size = ctypes.c_int(100)
    #设置指针类型
    p_pc_size = ctypes.pointer(pc_size)
    pointer_pc_array = sharelib.get_pc_array(p_pc_size)
    # print("w, h", pc_mat_h.value, pc_mat_w.value)
    # size=(pc_size.value,4)
    #数据转化成图像
    pc = np.reshape(  np.ctypeslib.as_array(pointer_pc_array,shape=(pc_size.value*4,1)),  (-1, 4) )
    # pc =  np.reshape(np.array(np.fromiter(pointer_pc_array, dtype=np.float, count=size[0]*size[1])) ,(-1, 4))
    return pc

def get_pc_flag():
    sharelib.get_pc_flag.restype = ctypes.c_int
    return sharelib.get_pc_flag()

def send_pc_pre_array(pc_pre):
    # pc_pre = np.squeeze( np.reshape(pc_pre, (1,-1)) )
    if not pc_pre.flags['C_CONTIGUOUS']:
        pc_pre = np.ascontiguous(pc_pre, dtype=pc_pre.dtype)  # 如果不是C连续的内存，必须强制转换
    p_pc_pre = ctypes.cast(pc_pre.ctypes.data, ctypes.POINTER(ctypes.c_float))   #转换为ctypes，这里转换后的可以直接利用ctypes转换为c语言中的int*，然后在c中使用
    sharelib.send_pc_pre_array(p_pc_pre, pc_pre.shape[0]*pc_pre.shape[1])



print("ciassd ok!")
while True:
    time.sleep(0.0001)#防止绝对的空循环导致CPu占用，其他进程无法修改共享内存
    if get_pc_flag() == 1:
        # a=0
        # for i in range(500000):
        #     a = 1+a
        #     print("a ", a)
        pc = get_pc_array()
        # print(pc)

    if get_pc_flag() == 2:
        print("write pre")
        pc_pre = np.reshape(np.array([1,2,3,4,5,6,7,1,2,3,4,5,6,7], dtype=np.float32), (2, 7))
        send_pc_pre_array(pc_pre)

